<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" class="title-but" @click="onAdd(1)" icon="plus">新增分类</a-button>
                <a-dropdown :trigger="['click']">
                  <a-menu slot="overlay" @click="(e) => this.checkSet(e.key)">
                    <a-menu-item :key="2">批量禁用</a-menu-item>
                    <a-menu-item :key="1">批量显示</a-menu-item>
                    <a-menu-item :key="0">批量删除</a-menu-item>
                  </a-menu>
                  <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /> </a-button>
                </a-dropdown>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>

    <div v-show="checkId.length" class="select-title">
      <a-alert :message="`已选择 ${checkId.length} 项`" type="info" show-icon />
    </div>
    <a-card :bordered="false" :bodyStyle="{ display: 'flex', justifyContent: 'space-around' }">
      <div style="width: 50%; padding-right: 30px" :bodyStyle="{ maxHeight: '580px', overflowY: 'auto' }">
        <div v-if="catList.length > 0">
          <el-tree
            :data="catList"
            @check-change="onCheck"
            @node-click="nodeClick"
            @current-change="onSelect"
            @node-drop="nodeDrop"
            draggable
            show-checkbox
            node-key="id"
            :default-expand-all="true"
            :expand-on-click-node="true"
          >
            <span
              @mouseover="mouseover(data, node)"
              @mouseout="mouseout"
              class="custom-tree-node flex-y-center flex-x-sb"
              style="flex: 1"
              slot-scope="{ node, data }"
            >
              <div class="flex-y-center">
                <i v-if="node.expanded == false && node.childNodes.length" class="el-icon-folder"></i>
                <i v-else class="el-icon-folder-opened"></i>
                <span>{{ data.name }} (ID:{{ data.id }})</span>
                <span v-if="data.is_show == 0" style="margin-left: 10px; color: #aaa"> (已禁用) </span>
              </div>
              <div>
                <span v-show="mouseoverData.id == data.id">
                  <el-button v-show="isShowAdd" type="text" size="mini" @click.stop="mouseAdd(data, node)">
                    新增
                  </el-button>
                  <el-button type="text" size="mini" @click.stop="mouseDel(data)">{{
                    data.is_show == 0 ? '显示' : '禁用'
                  }}</el-button>
                  <el-button type="text" size="mini" @click.stop="checkSet(0, data.id)"> 删除 </el-button>
                </span>
              </div>
            </span>
          </el-tree>
        </div>

        <a-empty v-else />
      </div>

      <a-affix :offset-top="100" style="flex: 1">
        <a-card :title="updated_at === '2' ? '编辑分类' : '新增分类'">
          <a-form
            action=""
            method="post"
            @submit="submitAdd"
            :form="form"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 12 }"
          >
            <a-form-item :labelCol="labelCol" :hidden="true" :wrapperCol="wrapperCol" label="父级分类">
              <a-input
                v-decorator="[
                  'parent_id',
                  { rules: [{ pattern: /((^[1-9]\d*)|^0)(\.\d{0,0}){0,1}$/, message: '父级ID格式不争取' }] },
                ]"
                type="number"
                :step="1"
              />
            </a-form-item>
            <a-form-item :labelCol="labelCol" :hidden="true" :wrapperCol="wrapperCol" label="ID">
              <a-input
                v-decorator="[
                  'id',
                  { rules: [{ pattern: /((^[1-9]\d*)|^0)(\.\d{0,0}){0,1}$/, message: 'ID格式不正确' }] },
                ]"
                type="number"
                :step="1"
              />
            </a-form-item>
            <a-form-item
              v-if="catInfo.parent_name"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="父级分类"
              hasFeedback
            >
              <a-input :disabled="true" v-decorator="['parent_name']" />
            </a-form-item>
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="分类名称" hasFeedback>
              <a-input
                v-decorator="[
                  'name',
                  {
                    rules: [
                      { required: true, message: '请填写名称' },
                      { max: 20, message: '名称不能大于20个字符' },
                    ],
                  },
                ]"
                placeholder="请填写分类名称"
              />
            </a-form-item>
            <a-form-item
              :hidden="true"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="排序"
              help="排序值越小排序越靠前"
              hasFeedback
            >
              <a-input
                v-decorator="[
                  'sort',
                  {
                    rules: [
                      { required: false, message: '填写排序' },
                      { pattern: /((^[1-9]\d*)|^0)(\.\d{0,0}){0,1}$/, message: '排序不对' },
                    ],
                  },
                ]"
                type="number"
                :step="1"
              />
            </a-form-item>
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="分类图标" hasFeedback>
              <div class="flex-col flex-x-sb">
                <div>
                  <div v-if="catInfo.pic_url" class="goods_pic_item_box">
                    <div class="upload-img-box">
                      <img :src="catInfo.pic_url" alt="" />
                      <div class="action-hover">
                        <div class="hover-bg"></div>
                        <div class="hover-body">
                          <div class="action-icons">
                            <a-icon @click="previewPic" type="eye" />
                            <a-icon @click="() => (this.catInfo.pic_url = '')" type="delete" />
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="upload-box">
                    <div class="upload-content">
                      <a-icon style="font-size: 24px; color: rgba(0, 0, 0, 0.45)" type="plus" />
                      <span>上传图片</span>
                    </div>
                    <div class="self-com">
                      <storage-select selectNum="1" @input="changeImg"></storage-select>
                    </div>
                  </div>
                </div>
                <div style="color: rgba(0, 0, 0, 0.45)">建议尺寸100 * 100</div>
              </div>
            </a-form-item>
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否显示">
              <a-radio-group v-decorator="['is_show']">
                <a-radio value="1"> 显示 </a-radio>
                <a-radio value="0"> 禁用 </a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
              <a-button type="primary" html-type="submit" :loading="status.butLoading"> 保存 </a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-affix>
    </a-card>

    <a-modal
      :visible="showPreviwModal"
      @ok="
        () => {
          showPreviwModal = fasle
        }
      "
      @cancel="
        () => {
          showPreviwModal = fasle
        }
      "
    >
      <div style="display: flex; justify-content: center">
        <img style="width: 300px" :src="previewImgSrc" alt="" />
      </div>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import { list, save, del, statusAll, dragChange } from '@/api/purchase/cat'
import pick from 'lodash.pick'

const statusLoading = {
  loading: true,
  showAdd: true, // 是否显示添加子分类按钮
  butLoading: false, // 提交按钮状态
  delLoading: false, // 删除按钮状态
  showLoading: false,
}

export default {
  components: {
    tabList: () => import('@/views/saas/components/tabList.vue'),
  },

  data() {
    return {
      tabList: [
        {
          key: 'saasPurchaseAuditList',
          name: '待审核商品',
        },
        {
          key: 'saasPurchaseAuditGoods',
          name: '云仓商品',
        },
        {
          key: 'saasSupplierCategory',
          name: '云仓分类',
        },
      ],

      updated_at: '1', // 1新增 2编辑
      isShowAdd: true,
      showPreviwModal: false,
      previewImgSrc: '',
      catList: [],
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
      catInfo: {},
      status: statusLoading,
      is_show: '-1', // 获取列表状态
      checkId: [], // 选择中ID
      is_pic: true,
      mouseoverData: {
        id: '',
      },
    }
  },

  created() {
    this.getList()
    this.onAdd(1)
  },

  watch: {
    catInfo(val) {
      this.setDataForm(val)
    },

    is_show(vale) {
      this.status.loading = true
      this.onAdd(1)
      this.getList()
    },
  },

  methods: {
    changeImg(val) {
      this.catInfo.pic_url = val
    },

    previewPic() {
      this.showPreviwModal = true
      this.previewImgSrc = this.catInfo.pic_url
    },

    updateCheck(res) {
      return false
    },

    getList() {
      list({ is_show: this.is_show }).then((res) => {
        this.status.loading = false
        this.catList = res.data
      })
    },

    mouseout() {
      this.mouseoverData = {
        id: '',
      }
    },

    // 鼠标移入事件
    mouseover(data, node) {
      this.mouseoverData = data

      if (node.level >= 3) {
        this.isShowAdd = false
      } else {
        this.isShowAdd = true
      }
    },

    nodeClick(data) {
      // this.mouseoverData = data
      this.catInfo = data
    },

    mouseAdd(data, node) {
      this.catInfo = {
        id: 0,
        parent_id: data.id,
        parent_name: data.name,
        is_show: '1',
        pic_url: '',
        sort: 100,
        name: '',
      }

      this.updated_at = '1'
    },

    // 单个禁用
    mouseDel(data) {
      var status = ''
      if (data.is_show == 0) {
        status = 1
      } else {
        status = 2
      }
      this.checkSet(status, data.id)
    },

    getMenu(list) {
      const arr = []
      list.forEach((el) => {
        const obj = {
          id: el.id,
        }

        if (el.children && Array.isArray(el.children)) {
          obj.children = this.getMenu(el.children)
        }

        arr.push(obj)
      })

      return arr
    },

    // 拖拽完成触发
    async nodeDrop() {
      let params = this.getMenu(this.catList)

      try {
        const res = await dragChange({
          list: JSON.stringify(params),
        })
        if (res.code != 0) throw res
        this.$message.success(res.msg)
        this.getList()
      } catch (res) {
        this.$message.error(res.msg)
      }
    },

    onSelect(e, node) {
      this.updated_at = '2'

      this.catInfo = e
      // 当前为三级分类 是否可以添加下级
      if (node.level == 3) {
        this.showAdd = false
      } else {
        this.showAdd = true
      }
      // return

      // 是否可以添加分类图标
      this.is_pic = true

      // return
      // // 当前选中信息
      // this.catInfo = this.getKeyData(e[0])
      // setTimeout(() => {
      //   this.is_pic = true
      // }, 100)
      // var indexArr = typeof e[0] === 'number' ? e : e[0].split('-')
      // if (indexArr.length === 3) {
      //   this.showAdd = false
      // }
    },

    onCheck(e, isSelect) {
      console.log(e, 'check')
      if (isSelect) {
        this.checkId.push(e.id)
      } else {
        this.checkId = this.checkId.filter((item) => {
          return item != e.id
        })
      }
      // 1.将选中id加入checkId

      // return
      // this.catInfo = e

      // var checkId = []
      // if (e.checked.length > 0) {
      //   e.checked.forEach((element) => {
      //     var catInfo = this.getKeyData(element)
      //     checkId.push(catInfo.id)
      //   })
      // }
      // this.checkId = checkId
      // console.log(this.checkId)
    },

    getKeyData(e) {
      var indexArr = typeof e === 'number' ? [e] : e.split('-')
      var catList = this.catList
      var catInfo = {}
      if (indexArr.length === 1) {
        catInfo = catList[indexArr[0]]
      } else if (indexArr.length === 2) {
        catInfo = catList[indexArr[0]].children[indexArr[1]]
      } else if (indexArr.length === 3) {
        catInfo = catList[indexArr[0]].children[indexArr[1]].children[indexArr[2]]
      }
      console.log(this.catList, 'catList')
      return catInfo
    },

    onDel(id) {
      this.$message.loading({ content: '提交中...', key: 'del' })
      del({ id: id || this.catInfo.id }).then((res) => {
        this.$message.success({ content: res.msg, key: 'del' })
        if (res.code === 0) {
          this.getList()
        }
      })
    },

    /**
     * 批量操作 status 0 删除 1 显示 2 隐藏
     *
     */
    checkSet(status, id) {
      var that = this
      var text = status == 0 ? '删除' : status == 1 ? '显示' : '禁用'
      this.$confirm({
        title: '是否确认' + text + '选中分类?',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          that.$message.loading({ content: '提交中...', key: 'checkSet' })

          del({
            type: status,
            ids: id || that.checkId.join(','),
          }).then((res) => {
            if (res.code === 0) {
              that.$message.success({ content: '提交成功!', key: 'checkSet', duration: 2 })
              that.getList()
            }
          })
        },
        onCancel() {
          console.log('Cancel')
        },
        class: 'test',
      })
    },

    submitAdd(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.status.butLoading = true
          values.pic_url = this.catInfo.pic_url
          save(values).then((res) => {
            this.status.butLoading = false
            this.$message.success(res.msg)
            if (res.code === 0) {
              this.getList()
            }
          })
        }
      })
    },

    setDataForm() {
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.catInfo, ['name', 'sort', 'is_show', 'parent_id', 'id', 'parent_name']))
      })
    },

    onAdd(isNew = 0) {
      if (isNew == 1) {
        this.updated_at = 1
      } else {
        this.updated_at = 2
      }
      this.catInfo = {
        id: 0,
        parent_id: this.catInfo && this.catInfo.id > 0 && isNew === 0 ? this.catInfo.id : 0,
        parent_name: this.catInfo && this.catInfo.id > 0 && isNew === 0 ? this.catInfo.name : '顶级分类',
        is_show: '1',
        pic_url: '',
        sort: 100,
        name: '',
      }
    },

    updateShow(status) {
      this.is_show = status
    },

    selectImg(e) {
      this.catInfo.pic_url = e
    },
  },
}
</script>
<style lang="less" scoped>
.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}

.title-but {
  margin-left: 6px;
}

.goods_pic_item_box {
  width: 80px;
  height: 80px;
  box-shadow: 0 0 5px rgba(170, 170, 170, 0.671);
  border-radius: 3px;
  position: relative;
  margin-right: 10px;
  width: 104px;
  height: 104px;
  background: rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.14901960784313725);
  opacity: 1;
  border-radius: 4px;
  float: left;
  margin: 0 8px 0 0px;
  padding: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  .upload-img-box {
    width: 88px;
    height: 88px;
    position: relative;
    .action-hover {
      width: 100%;
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
      z-index: 11;
      display: none;
      opacity: 0;
      transition: all 0.3s;

      .hover-bg {
        width: 100%;
        height: 100%;
        background-color: #000000;
        opacity: 0.4;
      }
      .hover-body {
        width: 100%;
        height: 100%;
        position: absolute;
        left: 0;
        top: 0;
        z-index: 11;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .action-icons {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 5px;
        .anticon {
          color: #ffffff;
          font-size: 17px;
        }
        .anticon:nth-child(1) {
          margin-right: 10px;
        }
      }
    }
    img {
      width: 100%;
      height: 100%;
      display: block;
    }
  }
  .upload-img-box:hover > .action-hover {
    display: block;
    opacity: 1;
  }
}
.upload-box {
  width: 104px;
  height: 104px;
  background: rgba(0, 0, 0, 0.05);
  border: 1px dashed rgba(0, 0, 0, 0.14901960784313725);
  opacity: 1;
  border-radius: 4px;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  float: left;
  .upload-content {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }
  .self-com {
    opacity: 0;
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 111;
    /deep/.ant-btn {
      width: 104px;
      height: 103px;
    }
    /deep/.ant-input-group-wrapper {
      width: 104px;
      height: 104px;
      .ant-input-group {
        width: 100%;
        height: 100%;
        span:nth-child(1) {
          display: none;
        }
        span:nth-child(3) {
          width: 100%;
          height: 100%;
          position: absolute;
          left: 0;
          top: 0;
        }
      }
    }
  }
}

/deep/.ant-card-head {
  background: #f5f5f5;
}

::v-deep {
  .el-button {
    color: #409eff !important;
  }
}
</style>
